package io.dcloud.h527baaa6;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.WindowManager;

import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import io.dcloud.h527baaa6.activity.WebActivity;
import io.dcloud.h527baaa6.base.BaseActivity;
import io.dcloud.h527baaa6.bean.XmlBean;
import io.dcloud.h527baaa6.utils.AlertDialogUtils;
import io.dcloud.h527baaa6.utils.AppContents;
import io.dcloud.h527baaa6.utils.NetWorkUtils;
import io.dcloud.h527baaa6.utils.SharePreUtils;
import io.reactivex.functions.Consumer;

public class SplashActivity extends BaseActivity {
    private static long SPLASH_MILLIS = 450;
    private boolean isDownload=false;
    private boolean isPermission=false;
    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected int getTitleText() {
        return 0;
    }

    @Override
    protected void initViewAndData() {
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        http();
        RxPermissions rxPermission = new RxPermissions(mContext);
        rxPermission.request(Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            // 用户已经同意该权限
                            isPermission=true;
                            if (isDownload){
                                WebActivity.startActivity(mContext,"http://cdwhdb.cccicc.org.cn/home/landmark");
                                finish();
                            }
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            AlertDialogUtils.showDialog(mContext, "请在设置中心打开定位权限", new AlertDialogUtils.OnPositiveListener() {
                                @Override
                                public void onPostive() {
                                    try {
                                        Intent localIntent = new Intent();//
                                        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                        localIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
                                        mContext.startActivity(localIntent);
                                    } catch (Exception e) {

                                    }
                                    finish();
                                }

                                @Override
                                public void onNegative() {
                                    finish();
                                }
                            });
                        }
                    }
                });

    }
   private void http(){
       NetWorkUtils.query(AppContents.key, XmlBean.class).subscribe(new Consumer<XmlBean>() {
           @Override
           public void accept(final XmlBean xmlBean) throws Exception {
               SharePreUtils.saveData(xmlBean,SplashActivity.this);//保存数据
               if (xmlBean.getCode()==0){
                   SharedPreferences sharedPreferences=getSharedPreferences("ly", Context.MODE_PRIVATE);
                   if (sharedPreferences.getInt("version_number",0)!=xmlBean.getData().getVersion_number()){
                       new Thread(new Runnable() {
                           @Override
                           public void run() {
                               downloadApk(xmlBean.getData().getPicxml(),getFilesDir().getAbsolutePath(),"ly.xml");
                               downloadApk(xmlBean.getData().getPicdat(),getFilesDir().getAbsolutePath(),"ly.dat");
                               isDownload=true;
                               SharedPreferences sharedPreferences=getSharedPreferences("ly", Context.MODE_PRIVATE);
                               SharedPreferences.Editor edit = sharedPreferences.edit();
                               edit.putInt("version_number",xmlBean.getData().getVersion_number());
                               edit.commit();
                               runOnUiThread(new Runnable() {
                                   @Override
                                   public void run() {
                                       if (isPermission){
                                           WebActivity.startActivity(mContext,"http://cdwhdb.cccicc.org.cn/home/landmark");
                                           finish();
                                       }
                                   }
                               });
                           }
                       }).start();
                   }else {
                       isDownload=true;
                       runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                               if (isPermission){
                                   WebActivity.startActivity(mContext,"http://cdwhdb.cccicc.org.cn/home/landmark");
                                   finish();
                               }
                           }
                       });
                   }
               }
           }
       });
   }
    @Override
    protected boolean isFullScreen() {
        return true;
    }
    /**
     * 下载文件
     * @param downloadUrl
     * @param path
     * @param name
     */
    private void downloadApk(String downloadUrl, String path, String name) {
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
        file=new File(path+"/"+name);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        InputStream ips = null;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("GET");
            huc.setReadTimeout(10000);
            huc.setConnectTimeout(3000);
            ips = huc.getInputStream();
            int length = huc.getContentLength();//文件的总长度
            int loadLength=0;//下载长度
            // 拿到服务器返回的响应码
            int hand = huc.getResponseCode();
            if (hand == 200) {
                // 建立一个byte数组作为缓冲区，等下把读取到的数据储存在这个数组
                byte[] buffer = new byte[8192];
                int len = 0;
                while ((len = ips.read(buffer)) != -1) {
                    loadLength+=len;
                    int progress= (int) (loadLength * 100.0F/ length);
                    fos.write(buffer, 0, len);
                }
                Log.i("sss","下载成功");
            } else {
                Log.i("sss","网络连接失败");
            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (ips != null) {
                    ips.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
